<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="套餐名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入名称" class="!w-240px" />
        <el-text type="info"
          ><span class="ml-5px">团购套餐名称，如：招牌双人餐、牙膏牙刷套装</span></el-text
        >
      </el-form-item>
      <el-form-item label="适用人数" prop="people">
        <div class="mb-10px mx-10px w-full">
          <el-slider
            v-model="computedPeople"
            range
            show-stops
            :min="MIN_PEOPLE"
            :max="MAX_PEOPLE"
            :marks="peopleMarks"
          />
        </div>
      </el-form-item>
      <el-form-item label="购买须知" prop="guidance">
        <div clas="flex flex-col">
          <el-table :data="formData.guidance" size="small" class="mb-10px">
            <template #empty>
              <span class="text-red-500">{{
                formData.guidance.length == 0 ? '请添加条目' : ''
              }}</span>
            </template>
            <el-table-column prop="value" label="条目值" min-width="200">
              <template #default="{ row, $index }">
                <el-input
                  v-model.trim="row.value"
                  maxlength="20"
                  :placeholder="'请输入条目值' + ($index + 1)"
                  clearable
                  show-word-limit
                />
              </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="120">
              <template #default="{ row }">
                <el-input
                  v-model.trim="row.sort"
                  :min="0"
                  :max="9999"
                  clearable
                  placeholder="请输入条目序号"
                  class="!w-[100px]"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="right" width="60" fixed="right">
              <template #default="{ row, $index }">
                <el-button type="danger" link @click="deleteGuidance(row, $index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="flex flex-row mt-5px">
            <el-button type="success" @click="addGuidance">添加条目</el-button>
            <el-text type="info"
              ><span class="ml-5px"
                >若条目存在多项值则用英文逗号隔开，如：解释权归商家所有、限购1次、周末不可使用。</span
              ></el-text
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item label="轮播图" prop="picUrls">
        <UploadImgs v-model="formData.picUrls" />
      </el-form-item>
      <el-form-item label="开关" prop="enabled">
        <el-switch
          v-model="formData.enabled"
          :active-value="true"
          :inactive-value="false"
          active-text="已上架"
          inactive-text="已下架"
          inline-prompt
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts" name="GrouponPackageForm">
import * as GrouponPackageApi from '@/api/mall/promotion/groupon/package'

const { t } = useI18n()
const message = useMessage()

const MIN_PEOPLE = 1
const MAX_PEOPLE = 11
const peopleMarks = computed(() => {
  const marks: Record<string, string> = {}
  for (let i = 1; i <= MAX_PEOPLE; i++) {
    marks[i] = i % 2 == 0 ? '' : i + '人'
  }
  return marks
})

const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const formData = ref<any>({
  id: undefined,
  name: undefined,
  minPeople: 3,
  maxPeople: 5,
  guidance: [
    {
      value: '不限',
      sort: 0
    }
  ],
  picUrls: undefined,
  enabled: true
})
const formRules = reactive({
  name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  people: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (formData.value.minPeople && formData.value.maxPeople) {
          callback()
          return
        }
        callback(new Error('请选择适用人数'))
      },
      trigger: ['blur', 'change']
    }
  ],
  guidance: [
    {
      required: true,
      validator: (_rule: any, _value: any, callback: any) => {
        if (formData.value.guidance && formData.value.guidance.length) {
          callback()
          return
        }
        callback(new Error('购买须知不能为空'))
      },
      trigger: ['blur', 'change']
    }
  ],
  picUrls: [{ required: true, message: '轮播图不能为空', trigger: ['blur', 'change'] }]
})
const formRef = ref()

const computedPeople = computed({
  get() {
    return [formData.value.minPeople, formData.value.maxPeople]
  },
  set(value) {
    formData.value.minPeople = value[0]
    formData.value.maxPeople = value[1]
  }
})

const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  console.log('type=' + type + ', id=' + id)
  if (id) {
    formLoading.value = true
    try {
      formData.value = await GrouponPackageApi.getDetailById(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open })

const emit = defineEmits(['success'])
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (
    formData.value.guidance
      .map((item: any) => {
        return item.value
      })
      .includes('')
  ) {
    message.error('购买须知不能有空值')
    return
  }
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await GrouponPackageApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      await GrouponPackageApi.updateById(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    minPeople: 3,
    maxPeople: 5,
    guidance: [
      {
        value: '不限',
        sort: 0
      }
    ],
    picUrls: undefined,
    enabled: true
  }
  formRef.value?.resetFields()
}

const addGuidance = () => {
  formData.value.guidance.push({
    value: '',
    sort: formData.value.guidance.length
  })
}
const deleteGuidance = (_item: any, index: any) => {
  formData.value.guidance.splice(index, 1)
}
</script>
